import { type User } from '@/models/userinfo'
/*
获取登录设置
- 记住密码
- 自动登录
*/
export function getRememberPas() {
  return localStorage.getItem('rememberPassword') === 'true'
}
export function setRememberPas(rem: boolean) {
  localStorage.setItem('rememberPassword', rem.toString())
}

export function delRememberPas() {
  localStorage.removeItem('rememberPassword')
}
/*
存储用户信息
- 账号
- 密码
- token
*/
export function getUser() {
  const acc = localStorage.getItem('account')
  const pas = localStorage.getItem('password')
  const aT = localStorage.getItem('accessToken')
  const rT = localStorage.getItem('refreshToken')
  const name = localStorage.getItem('name')
  const userId = localStorage.getItem('userId')
  const profile = localStorage.getItem('profile')
  const user: User = {
    account: atob(acc == null ? '' : acc),
    password: atob(pas == null ? '' : pas),
    accessToken: atob(aT == null ? '' : aT),
    refreshToken: atob(rT == null ? '' : rT),
    name: name || '',
    profile: atob(profile == null ? '' : profile),
    userId: userId == null ? 0 : Number.parseInt(userId)
  }
  return user
}
export function setUser(
  ac: string,
  accessToken: string,
  refreshToken: string,
  role: string,
  name: string,
  profile: string,
  userId: number,
  pw?: string
) {
  localStorage.setItem('account', btoa(ac))
  localStorage.setItem('accessToken', btoa(accessToken))
  localStorage.setItem('refreshToken', btoa(refreshToken))
  localStorage.setItem('role', btoa(role))
  localStorage.setItem('profile', btoa(profile))
  localStorage.setItem('name', name)
  localStorage.setItem('userId', userId.toString())
  if (pw !== undefined && pw !== '') {
    localStorage.setItem('password', btoa(pw))
  }
}
export function setPassword(password: string) {
  localStorage.setItem('password', btoa(password))
}
export function delUserInfo() {
  localStorage.removeItem('account')
  localStorage.removeItem('password')
  localStorage.removeItem('accessToken')
  localStorage.removeItem('refreshToken')
  localStorage.removeItem('name')
  localStorage.removeItem('profile')
  localStorage.removeItem('userId')
  delRememberPas()
}
export function getAccessToken() {
  const aT = localStorage.getItem('accessToken')
  return atob(aT == null ? '' : aT)
}
export function getRefreshToken() {
  const rT = localStorage.getItem('refreshToken')
  return atob(rT == null ? '' : rT)
}
export function getRole() {
  const role = localStorage.getItem('role')
  return atob(role == null ? '' : role)
}
export function isAuth() {
  const token = localStorage.getItem('accessToken')
  const isAuth = token != null && token != '' && token != undefined
  return isAuth
}
